package com.yunhe.realtime.controller.data;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.model.DomainList;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.model.data.Measurement;
import com.yunhe.common.model.data.MeasurementReqDTO;
import com.yunhe.realtime.service.data.RealtimeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.yunhe.common.util.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 量测实时服务Controller
 * @author liuronglei
 * @version 1.7.0
 */
@Api(value = "realtime",description = "量测实时数据", tags = {"Data_Realtime"})
@RestController
@EnableAsync
@RequestMapping("/measurements/realtime")
public class RealtimeController {
    private static Logger logger = LoggerFactory.getLogger(RealtimeController.class);
    @Autowired
    private RealtimeService realtimeService;

    /**
     * 根据点号获得量测实时值
     * @param pointNumber 点号
     */
    @ApiOperation("根据点号获得量测实时值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pointNumber", value = "点号，多个点号用逗号隔开，如“101,102”", required = true, dataType = "long", paramType = "query")
    })
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<ResultObject> getMeasureRealtime(@RequestParam("pointNumber") Optional<List<Long>> pointNumber)
            throws ObjectNotFoundException {
        if (!pointNumber.isPresent()) {
            throw new ObjectNotFoundException("点号不能为空");
        }
        Map<Long, Double> realtime = realtimeService.findMeasureRealtime(pointNumber.get());
        return new ResponseEntity<>(new ResultObject<>(realtime), HttpStatus.OK);
    }

    @ApiOperation("根据点号获得量测实时值")
    @RequestMapping(value = "/batchGet", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> getMeasureRealtime(@RequestBody MeasurementReqDTO map) {
        List<Long> pointNumber = map.getPointNumber();
        if (CollectionUtil.isEmpty(pointNumber)) {
            return new ResponseEntity<>(new ResultObject<>(new HashMap<>()), HttpStatus.OK);
        }
        Map<Long, Double> realtime = realtimeService.findMeasureRealtime(pointNumber);
        return new ResponseEntity<>(new ResultObject<>(realtime), HttpStatus.OK);
    }

    /**
     * 设置量测实时值
     * @param pointNumber 点号
     * @param value 量测值
     */
    @ApiOperation("设置量测实时值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pointNumber", value = "点号", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "value", value = "量测值", required = true, dataType = "double", paramType = "query")
    })
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<ResultObject> saveMeasureRealtime(@RequestParam("pointNumber") Long pointNumber,
                                                            @RequestParam("value") Double value) {
        realtimeService.saveMeasureRealtime(pointNumber, value);
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    /**
     * 批量保存量测实时值（异步执行）
     * 为了避免处理时间过长，导致返回报错，故采用异步执行
     * @param pointNumberValueMap 点号Map
     */
    @ApiOperation("批量保存量测实时值（异步执行）")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/batch", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> saveMeasureRealtime(@RequestBody Map<Long, Double> pointNumberValueMap)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException, JsonProcessingException {
        realtimeService.saveMeasureRealtimeAsync(pointNumberValueMap);
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    /**
     * 批量删除量测实时值（异步执行）
     * 为了避免处理时间过长，导致返回报错，故采用异步执行
     * @param pointNumbers 点号列表
     */
    @ApiOperation("批量保存量测实时值（异步执行）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pointNumber", value = "点号", required = true, dataType = "long", paramType = "query")
    })
    @RequestMapping(value = "/batch", method = RequestMethod.DELETE)
    public ResponseEntity<ResultObject> deleteMeasureRealtime(@RequestParam("pointNumber") List<Long> pointNumbers) {
        realtimeService.delAsync(pointNumbers);
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    /**
     * 根据点号获得量测实时对象
     * @param pointNumber 点号
     */
    @ApiOperation("根据点号获得量测实时值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pointNumber", value = "点号，多个点号用逗号隔开，如“101,102”", required = true, dataType = "long", paramType = "query")
    })
    @RequestMapping(value = "/object", method = RequestMethod.GET)
    public ResponseEntity<ResultObject> getMeasureRealtimeObj(@RequestParam("pointNumber") List<Long> pointNumber) {
        Map<Long, Measurement> realtime = realtimeService.findMeasureRealtimeObj(pointNumber);
        return new ResponseEntity<>(new ResultObject<>(realtime), HttpStatus.OK);
    }

    @ApiOperation("根据点号批量获得量测实时值")
    @RequestMapping(value = "/object/batchGet", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> getMeasureRealtimeObj(@RequestBody MeasurementReqDTO map) {
        List<Long> pointNumber = map.getPointNumber();
        Map<Long, Measurement> realtime = realtimeService.findMeasureRealtimeObj(pointNumber);
        return new ResponseEntity<>(new ResultObject<>(realtime), HttpStatus.OK);
    }

    /**
     * 设置量测实时对象
     * @param measurement 量测对象
     */
    @ApiOperation("设置量测实时值")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/object", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> saveMeasureRealtimeObj(@RequestBody Measurement measurement) {
        realtimeService.saveMeasureRealtimeObj(measurement);
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    /**
     * 批量保存量测实时对象列表（异步执行）
     * 为了避免处理时间过长，导致返回报错，故采用异步执行
     * @param list 量测对象列表
     */
    @ApiOperation("批量保存量测实时列表（异步执行）")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/object/batch", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> saveMeasureRealtimeObj(@RequestBody DomainList<Measurement> list) {
        realtimeService.saveMeasureRealtimeObjAsync(list.getList());
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    /**
     * 清空量测实时备份
     * @param map 点号列表
     */
    @ApiOperation("清空量测实时备份")
    @RequestMapping(value = "/clearBackup", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> clearBackup(@RequestBody MeasurementReqDTO map) {
        List<Long> pointNumber = map.getPointNumber();
        if (pointNumber != null && pointNumber.size() > 0) {
            realtimeService.delBackupAsync(pointNumber);
        }
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    /**
     * 将量测实时对象转为备份
     * @param map 点号列表
     */
    @ApiOperation("将量测实时对象转为备份")
    @RequestMapping(value = "/movetoBackup", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> movetoBackup(@RequestBody MeasurementReqDTO map) {
        List<Long> pointNumber = map.getPointNumber();
        if (pointNumber != null && pointNumber.size() > 0) {
            realtimeService.movetoBackupAsync(pointNumber);
        }
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }

    /**
     * 获得量测实时对象备份
     * @param map 点号列表
     */
    @ApiOperation("获得量测实时对象备份")
    @RequestMapping(value = "/getBackup", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> getBackup(@RequestBody MeasurementReqDTO map) {
        Map<Long, Double> realtime = null;
        List<Long> pointNumber = map.getPointNumber();
        if (pointNumber != null && pointNumber.size() > 0) {
            realtime = realtimeService.getBackup(pointNumber);
        }
        return new ResponseEntity<>(new ResultObject<>(realtime), HttpStatus.OK);
    }

    /**
     * 更新量测实时对象
     * @param pointNumber 点号
     * @param rtime 时间戳
     * @param dtime 时间字符串
     * @param val 值
     * @param flag 标记
     */
    @ApiOperation("更新量测实时对象")
    @ApiImplicitParams({
    })
    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<ResultObject> updateMeasureRealtime(@RequestParam("pointNumber") Long pointNumber,
                                                              @RequestParam("rtime") Optional<Long> rtime,
                                                              @RequestParam("dtime") Optional<String> dtime,
                                                              @RequestParam("val") Optional<Double> val,
                                                              @RequestParam("flag") Optional<Integer> flag)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException, JsonProcessingException {
        realtimeService.updateMeasureRealtime(pointNumber, rtime.orElse(null), dtime.orElse(null),
                val.orElse(null), flag.orElse(null));
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }
}